package com.erp.serviceIMP;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.danga.MemCached.MemCachedClient;
import com.erp.dao.UomDAO;
import com.erp.entity.Uom;
import com.erp.exception.MyException;
import com.erp.service.UomService;

@Service(value="uomService")
public class UomServiceIMP implements UomService{

    @Autowired
    private MemCachedClient memcachedClient;
    @Autowired
    private UomDAO uomMapper;
    
    public MemCachedClient getMemcachedClient() {
        return memcachedClient;
    }

    public void setMemcachedClient(MemCachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }

    public UomDAO getUomMapper() {
        return uomMapper;
    }

    public void setUomMapper(UomDAO uomMapper) {
        this.uomMapper = uomMapper;
    }

    public List<Uom> findAll() {
        List<Uom> list = new ArrayList<Uom>();
        try {
            Uom uom = null;
            for (int i = 0; i < maxRecord; i++) {
                uom = (Uom) memcachedClient.get(keyStrategy(i));
                if (uom != null) {
                    list.add(uom);
                }
            }
            if (list.size() == 0) {
                list = uomMapper.findAll();
                for (Uom uo : list) {
                    memcachedClient.add(keyStrategy(uo.getId()), uo);
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return list;
    }

    public Uom findById(int id) {
        Uom uom = (Uom) memcachedClient.get(keyStrategy(id));
        if(uom==null){
            uom = uomMapper.findById(id);
            if(uom!=null){
                memcachedClient.add(keyStrategy(id), uom);
            }
        }
        return uom;
    }

    public void update(Uom uom) throws Exception {
        uomMapper.update(uom);
        memcachedClient.set(keyStrategy(uom.getId()), uomMapper.findById(uom.getId()));        
    }

    public int insert(Uom uom) throws Exception {
        uomMapper.insert(uom);
        int id = uom.getId();
        memcachedClient.add(keyStrategy(id), uom);
        return id;
    }

    public void delete(int id) throws Exception {
        uomMapper.delete(id);
        memcachedClient.delete(keyStrategy(id));
    }
    

    private static final int maxRecord=9999;

    private String keyStrategy(int id){
        return "uom" + id;
    }
    
}
